package com.czy.daishusys.ui.message;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.czy.daishusys.R;
import com.czy.daishusys.db.UserHelper;
import com.czy.daishusys.entity.StaffModel;
import com.czy.daishusys.global.Constants;
import com.czy.daishusys.ui.BaseActivity;
import com.czy.daishusys.utils.GsonUtils;
import com.czy.daishusys.utils.IntentUtils;
import com.czy.daishusys.utils.MyLog;
import com.czy.daishusys.utils.PhoneUtils;
import com.czy.daishusys.utils.glide.GlideUtils;
import com.czy.daishusys.widget.MyRecyclerView;
import com.czy.daishusys.widget.RightArrowButton;
import com.easemob.cases.MessageHelper;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.easeui.domain.EaseUser;
import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.callback.CallBack;
import com.zhouyou.http.exception.ApiException;
import com.zhouyou.http.model.HttpParams;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
/**
 * Created by hedepu on 2017/12/4
 * 员工详情
 */
public class ContactsDetailActivity extends BaseActivity {

    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.toolbar_subtitle)
    TextView toolbarSubtitle;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.appbar)
    AppBarLayout appbar;
    @BindView(R.id.tv_contacts_name)
    TextView tvContactsName;
    @BindView(R.id.tv_contacts_info)
    TextView tvContactsInfo;
    @BindView(R.id.ll_call_phone)
    LinearLayout llCallPhone;
    @BindView(R.id.ll_send_msg)
    LinearLayout llSendMsg;
    @BindView(R.id.rbtn_member_num)
    RightArrowButton rbtnMemberNum;
    @BindView(R.id.rbtn_server_order)
    RightArrowButton rbtnServerOrder;
    @BindView(R.id.rbtn_phone)
    RightArrowButton rbtnPhone;
    @BindView(R.id.rbtn_work_age)
    RightArrowButton rbtnWorkAge;
    @BindView(R.id.rbtn_skill_area)
    RightArrowButton rbtnSkillArea;
    @BindView(R.id.recyler_view_skill)
    MyRecyclerView recylerViewSkill;
    @BindView(R.id.scroll_view)
    ScrollView scrollView;
    @BindView(R.id.img_head)
    CircleImageView imgHead;

    private StaffModel staffModel;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_contacts_detail;
    }

    @Override
    protected void initInjector() {
        if (PhoneUtils.isEmpty(getIntent().getStringExtra("storeEmployeesId"))) {
            PhoneUtils.ShowToastMessage(this, getResources().getString(R.string.finish_parameter_anomaly));
            finish();
        }

    }

    @Override
    protected void initViews() {
        getToolbarTitle().setText(R.string.detail_info);
        scrollView.smoothScrollTo(0, 0);
        postUserDetails();
    }

    @OnClick({R.id.ll_call_phone, R.id.ll_send_msg})
    protected void OnViewClick(View view) {
        switch (view.getId()) {
            case R.id.ll_call_phone:
                if (staffModel != null)
                    IntentUtils.onClickCallPhone(ContactsDetailActivity.this, staffModel.getPhone());
                break;
            case R.id.ll_send_msg:
                if (staffModel == null || PhoneUtils.isEmpty(staffModel.getImKey())) {
                    return;
                }
                setResult(RESULT_OK);
//                finish();
                EaseUser easeUser = new EaseUser(staffModel.getImKey());
                easeUser.setNick(staffModel.getStoreName());
                easeUser.setAvatar(staffModel.getUserLogo());
                MessageHelper.getInstance().saveContact(easeUser);
                Intent intent = new Intent(ContactsDetailActivity.this, ChatActivity.class);
                intent.putExtra(EaseConstant.EXTRA_USER_ID, staffModel.getImKey());
                startActivity(intent);
                break;
        }
    }

    //设置详情数据
    public void setText() {
        initRecyclerView();
        tvContactsName.setText(staffModel.getEmployeesName());
        Drawable nav_up;
        if ("1".equals(staffModel.getSex())) {
            nav_up = getResources().getDrawable(R.mipmap.ic_male_tag);

//            tvContactsName.setCompoundDrawables(null, null, getResources().getDrawable(R.mipmap.ic_male_tag), null);
        } else {
            nav_up = getResources().getDrawable(R.mipmap.ic_female_tag);
        }
        nav_up.setBounds(0, 0, nav_up.getMinimumWidth(), nav_up.getMinimumHeight());
        tvContactsName.setCompoundDrawables(null, null, nav_up, null);

        tvContactsInfo.setText(String.format(getResources().getString(R.string.message_contacts_info), staffModel.getNickName() + "  " + staffModel.getPositionName()));
        rbtnMemberNum.setRightText(staffModel.getStoreEmployeesMembersCount());
        rbtnServerOrder.setRightText(staffModel.getServiceOrderCount());
        rbtnPhone.setRightText(staffModel.getPhone());
        rbtnWorkAge.setRightText(staffModel.getJobYear() + "年");
//        rbtnSkillArea;
        GlideUtils.loadImage(this, staffModel.getUserLogo(), imgHead, new GlideUtils.ImageLoadListener<String, GlideDrawable>() {
            @Override
            public void onLoadingComplete(String uri, ImageView view, GlideDrawable resource) {

            }

            @Override
            public void onLoadingError(String source, Exception e) {

            }
        }, R.mipmap.icon_order_member_default, R.mipmap.icon_order_member_default);
    }

    //获取员工详情
    public void postUserDetails() {

        HttpParams params = new HttpParams();
        params.put("session", UserHelper.getInstance().getSession(this));
        params.put("storeEmployeesId", getIntent().getStringExtra("storeEmployeesId"));
        params.put("pid",UserHelper.getInstance().getDevicePid());
        EasyHttp.post(Constants.SYS_USER_INFO_DTOREEMPSINFO)
                .params(params)
                .timeStamp(true)//添加时间戳
                .execute(new CallBack<String>() {
                    @Override
                    public void onStart() {
                        mMProgressDialog.show(getResources().getString(R.string.loading_text));
                    }

                    @Override
                    public void onCompleted() {
                        mMProgressDialog.dismiss();
                    }

                    @Override
                    public void onSuccess(String result) {
                        MyLog.e("EasyHttp", result);
                        String data = PhoneUtils.checkResponseFlag(ContactsDetailActivity.this, result);
                        if (!PhoneUtils.isEmpty(data)) {
                            staffModel = GsonUtils.fromJson(data, StaffModel.class);
                            setText();
                        }
                    }

                    @Override
                    public void onError(ApiException e) {
                        mMProgressDialog.dismiss();
                    }
                });


    }


    @Override
    protected void updateViews() {

    }


    private void initRecyclerView() {
        List<String> mDataList = new ArrayList<>();
        if (!PhoneUtils.isEmpty(staffModel.getLabels())) {
            String[] arr = staffModel.getLabels().split(",");
            mDataList.addAll(Arrays.asList(arr));
        }
        GridLayoutManager mgr = new GridLayoutManager(this, 3);
        mgr.setAutoMeasureEnabled(true);
        recylerViewSkill.setNestedScrollingEnabled(false);
        recylerViewSkill.setLayoutManager(mgr);
        BaseQuickAdapter mAdapter = new SkillTagAdapter(R.layout.item_view_skill_tag, mDataList);
        recylerViewSkill.setAdapter(mAdapter);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    public class SkillTagAdapter extends BaseQuickAdapter<String, BaseViewHolder> {

        int[] tagBgId = {R.drawable.shape_skill_tag_color1,
                R.drawable.shape_skill_tag_color2,
                R.drawable.shape_skill_tag_color3,
                R.drawable.shape_skill_tag_color4,
                R.drawable.shape_skill_tag_color5};

        public SkillTagAdapter(int layoutResId, List data) {
            super(layoutResId, data);
        }

        @Override
        protected void convert(BaseViewHolder helper, String item) {
            helper.setText(R.id.root, item);
            helper.setBackgroundRes(R.id.root, tagBgId[helper.getLayoutPosition() % 5]);
        }
    }

}
